import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { STColumn, STData } from '@delon/abc'
import { ACLService } from '@delon/acl'
import { SettingsService } from '@delon/theme'

import { I18NService } from '@core'
import { StoreService } from '../store.service'
import { IStoreQueryParams, Store } from '@shared/interfaces/store'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { ISearchSchema, ISearchOption } from '@shared/interfaces/search'
import { ESearchType, ETradeChannel, EPaymentBrand } from '@shared/enums'
import { Country, Currency } from '@shared/interfaces/common'
import { AAMSFilterInit } from '@shared/interfaces/aams'
import { openDownloadDialog } from 'app/utils/helpers'
import { ModalService } from '@shared/services/modal.service'
import { Observable } from 'rxjs'
import { ChannelService } from '@shared/services/channel.service'

@Component({
  selector: 'app-store-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class StoreListComponent extends ListBaseClass<Store, IStoreQueryParams> implements OnInit, AAMSFilterInit {
  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>
  @ViewChild('tplGroup') tplGroup: TemplateRef<void>
  @ViewChild('tplMerchant') tplMerchant: TemplateRef<void>
  @ViewChild('tplStore') tplStore: TemplateRef<void>
  @ViewChild('tplCountry') tplCountry: TemplateRef<void>
  @ViewChild('tplCurrency') tplCurrency: TemplateRef<void>
  @ViewChild('tplChannel') tplChannel: TemplateRef<void>

  data: Store[] = []
  selectedCountry: Country
  selectedCurrency: Currency
  /** 渠道选项 */
  channelOptions$: Observable<ISearchOption[]>
  selectedChannel: EPaymentBrand

  // query form definition
  searchSchema: ISearchSchema[] = []
  customSchema: ISearchSchema[] = []
  columns: STColumn[] = []

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public settings: SettingsService,
    public aclService: ACLService,
    private storeService: StoreService,
    private modalService: ModalService,
    private channelService: ChannelService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit(): void {
    this.initChannelOptions()
    this.initColumns()
    this.searchSchema = this.generateSearchSchema()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
    })
    // Call parent aams data
    this.initialAAMSFilter()
  }

  initialAAMSFilter() {
    this.initAcquirer()
    this.initAgent()
    this.initMerchant()
    this.initStore()
  }

  goNew(): void {
    this.router.navigate(['../new'], { relativeTo: this.route })
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.storeService.getList(this.params).subscribe(this.renderList.bind(this), this.getListError.bind(this))
  }

  viewDetail(record: Store): void {
    const { intStoreCode } = record.common
    this.router.navigate([`../${intStoreCode}`], { relativeTo: this.route })
  }

  /** 导出单条 */
  export(record: STData): void {
    const { intStoreCode } = record.common
    const params: IStoreQueryParams = {
      page: this.params.page,
      size: this.params.size,
      intStoreCode,
    }
    this.goExport(params)
  }

  /** 批量导出 */
  exportAll(): void {
    this.goExport(this.params)
  }

  /** 冻结对话框 */
  freezeDialog(record: Store): void {
    const { storeName } = record.common
    const msg = this.trans('GENERAL.NOTIFICATION.STORE_FREEZE_CONFIRM', { storeName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.freeze(record)
    })
  }

  /** 解冻对话框 */
  unfreezeDialog(record: Store): void {
    const { storeName } = record.common
    const msg = this.trans('GENERAL.NOTIFICATION.STORE_UNFREEZE_CONFIRM', { storeName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.unfreeze(record)
    })
  }

  /** 冻结 */
  freeze(record: Store): void {
    const { intStoreCode } = record.common
    this.storeService.freeze(intStoreCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  /** 解冻 */
  unfreeze(record: Store): void {
    const { intStoreCode } = record.common
    this.storeService.unfreeze(intStoreCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  private goExport(params: IStoreQueryParams): void {
    this.storeService.getStoreReport(params).subscribe(data => {
      const { url } = data
      openDownloadDialog(url, '导出门店')
    })
  }

  private initColumns() {
    const canUnlock = this.aclService.canAbility('api.put.camel.store.one.unfreeze')
    const canLock = this.aclService.canAbility('api.put.camel.store.one.freeze')
    const canDownload = this.aclService.canAbility('api.get.camel.stores.report')
    this.columns = [
      {
        type: 'link',
        title: '门店编号',
        i18n: 'GENERAL.STORE.NUM',
        index: 'common.storeNum',
        className: 'text-center',
        width: '200px',
        fixed: 'left',
        click: this.viewDetail.bind(this),
      },
      {
        title: '门店名称',
        i18n: 'GENERAL.STORE.NAME',
        index: 'common.storeName',
        width: '370px',
        className: 'text-left',
      },
      {
        title: '门店英文名称',
        i18n: 'GENERAL.STORE.NAME_EN',
        index: 'common.storeNameEN',
        width: '370px',
        className: 'text-left',
      },
      {
        title: '国家/地区',
        i18n: 'GENERAL.INFO.COUNTRY_REGION',
        index: 'common.address.nation',
        width: '100px',
        className: 'text-center',
      },
      {
        title: '创建时间',
        i18n: 'GENERAL.INFO.CREATED_AT',
        index: 'createdAt',
        className: 'text-center',
        type: 'date',
        dateFormat: 'YYYY-MM-DD HH:mm',
        width: '300px',
      },
      {
        title: '操作',
        i18n: 'GENERAL.INFO.OPERATION',
        width: '150px',
        fixed: 'right',
        className: 'text-center p-xs',
        iif: () => canLock || canUnlock || canDownload,
        buttons: [
          {
            text: '',
            icon: {
              iconfont: 'icon-download-twotone',
              type: 'iconfont',
            },
            click: this.export.bind(this),
            iif: () => canDownload,
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-lock-twotone',
              type: 'iconfont',
            },
            click: this.freezeDialog.bind(this),
            iif: record => canLock && record.common.status === 'normal',
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-unlock-circle',
              type: 'iconfont',
            },
            click: this.unfreezeDialog.bind(this),
            iif: record => canUnlock && record.common.status === 'freeze',
          },
        ],
      },
    ]
  }

  private generateSearchSchema(): ISearchSchema[] {
    return [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: ['createdAtFrom', 'createdAtTo'],
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'GENERAL.BIZ_LEVEL.INSTITUT ION',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'GENERAL.BIZ_LEV EL.AGENT',
        labelI18n: 'GENERAL.BIZ_LEVEL.AGENT',
        index: 'agentCode',
        component: this.tplGroup,
        customFunc: () => this.selectedGroup && this.selectedGroup.code,
      },
      {
        label: 'GENERAL.BIZ_L EVEL.MERCHANT',
        labelI18n: 'GENERAL.BIZ_LEVEL.MERCHANT',
        index: 'intMerCode',
        component: this.tplMerchant,
        customFunc: () => this.selectedMerchant && this.selectedMerchant.code,
      },
      {
        label: 'GENER AL.BIZ_LEVEL.STORE',
        labelI18n: 'GENERAL.BIZ_LEVEL.STORE',
        index: 'intStoreCode',
        component: this.tplStore,
        customFunc: () => this.selectedStore && this.selectedStore.code,
      },
      {
        label: 'GENE RAL.INFO.COUNTRY_REGION',
        labelI18n: 'GENERAL.INFO.COUNTRY_REGION',
        index: 'nation',
        component: this.tplCountry,
        customFunc: () => this.selectedCountry && this.selectedCountry.codeAlpha3,
      },
      {
        label: 'GENER AL.INFO.TRANSACTION_CURRENCY',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        index: 'currency',
        component: this.tplCurrency,
        customFunc: () => this.selectedCurrency && this.selectedCurrency.code,
      },
      {
        label: 'GENERAL.INFO.CHANNEL',
        labelI18n: 'GENERAL.INFO.CHANNEL',
        index: 'channel',
        component: this.tplChannel,
        customFunc: () => this.selectedChannel,
      },
       {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        type: ESearchType.selection,
        options: [
          { label: this.trans('GENERAL.STATUS.NORMAL'), value: 'normal' },
          { label: this.trans('GENERAL.STATUS.FREEZE'), value: 'freeze' },
        ],
      },
    ]
  }

  private initChannelOptions(): void {
    this.channelOptions$ = this.channelService.getCurrentSupportChannelOptions()
  }
}
